package com.gule.gl.leetcode.editor.cn;

import com.gule.gl.leetcode.editor.cn.definition.ListNode;

import java.util.Objects;

/**
 * 从单链表中找出第k个元素
 */
public class LinkedListFindK {
    public static void main(String[] args) {
        Solution solution = new LinkedListFindK().new Solution();

    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * class ListNode {
     * int val;
     * ListNode next;
     * ListNode(int x) {
     * val = x;
     * next = null;
     * }
     * }
     */
    public class Solution {

        /**
         * 初始化两个指针，第二个比第一个先快K个，然后两个一起移动
         *
         * @param head
         * @return
         */
        public ListNode hasCycle(ListNode head, int k) {
            if (Objects.isNull(head) || Objects.isNull(head.next)) {
                return null;
            }
            ListNode point1 = head;
            ListNode point2 = head;
            for (int i = 0; i < k; i++) {
                if (Objects.isNull(head.next)) {
                    return null;
                }
                point2 = point2.next;
            }
            while (Objects.nonNull(point2.next)) {
                point2 = point2.next;
                point1 = point1.next;
            }
            return point1;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
